#include "listDir.h"
char* listDir(char *path,int flag, char *destination)
{
	if(mh==NULL)
		return ERR_VFS_LISTDIR_03;
	int z=strlen(path);
	if(z!=1 && path[z-1]=='/')
		path[z-1]='\0';
	int ret = -1;
	// Copy the destination file name in char array
	char destFileName[100];
	strcpy(destFileName,destination);
	
	//tokenize the path
	char dirpath[100];
	strcpy(dirpath,path);
	char *tokens[20];
	int i=0,j=0;	
	if(nAryRoot==NULL)
	{
		return ERR_VFS_LISTDIR_01;
	}
	tokens[i]=strtok(dirpath,"/");
	while(tokens[i]!=NULL)
	{
		i++;
		tokens[i]=strtok(NULL,"/");
	}
	j = i;
	i=0;

	//Traverse till the directory whose children have to be listed
	nAryNode *temp=nAryRoot;
	
	if((tokens[i]!=NULL)&&(nAryRoot==NULL))
	{
		return ERR_VFS_LISTDIR_01;
	}
	if(strcmp(temp->name,"/")==0)
	{
		if(temp->child!=NULL)
			temp  = temp->child;
		else
			return ERR_VFS_LISTDIR_01;
	}
	
	while(tokens[i] != NULL && temp!=NULL)
	{	
			while((strcmp(tokens[i],temp->name)!=0)&&((temp->sibling)!=NULL))		
			{
				temp=temp->sibling;
			}
			if(strcmp(tokens[i],temp->name)!=0)
			{
				return ERR_VFS_LISTDIR_01;
			}
			i++;
			if((tokens[i]!=NULL) && (temp->child==NULL) )
			{
				return ERR_VFS_LISTDIR_01;
			}
			else
				temp = temp->child;
								
	}
	if(flag !=0 && flag !=1)
	{
		return ERR_VFS_LISTDIR_02;
	}
	else
	{
		FILE *fp = fopen(destFileName,"wb"); //Write the output to a file
		if(fp == NULL)
		{
			return ERR_VFS_LISTDIR_04;
		}
		while(temp!=NULL)
		{
			if(flag == 0) // Non-recursive listing of directory content
			{
				for (i = 0; i < j+1;i++)
					fprintf(fp,"%s","-");
				fprintf(fp,"%s\n",temp->name);
				temp=temp->sibling;
			}
			else if (flag == 1) // Recursive listing of directory content
			{
				fprintf(fp,"%s","-");
				ret = preorderTraversal(temp,fp,j);
				if(ret)
					break;			
			}
		}
		//fclose(fp);
		
	}
	return "SUCCESS";
					
}

int preorderTraversal(nAryNode *temp,FILE *fp, int j)
{
	int i;
	if(temp != NULL)
	{
		
		for(i = 0 ; i < j; i++)
			fprintf(fp,"%s","-");
		fprintf(fp,"%s\n",temp->name);
		preorderTraversal(temp->child,fp,j+1);
		preorderTraversal(temp->sibling,fp,j+1);
	}
	return 1;
}
